import { Form, Input, Button, Modal } from 'antd'
import { toWei } from '../utils'

export default function OrderForm({ open, hideModal }) {
  const [form] = Form.useForm()

  const onFinish = async (values: any) => {
    const { account, exchange, token } = window.web
    const ethAddress = '0x0000000000000000000000000000000000000000'
    const tokenAddress = token.options.address
    await exchange.methods.makeOrder(ethAddress, toWei(values.eth), tokenAddress, toWei(values.min)).send({
      from: account
    })
    hideModal()
    form.resetFields()
  }

  const comfirm = () => {
    form.submit()
  }

  return (
    <>
      <Modal
        title='创建订单'
        open={ open }
        onOk={ comfirm }
        onCancel={ hideModal }
      >
        <Form
          form={form}
          onFinish={onFinish}
          initialValues={{
            eth: '0',
            min: '0',
          }}
        >
          <Form.Item name="eth" label="购入eth" rules={[
            { 
              required: true,
              validator: (_, value) => {
                if (value > 0) {
                  return Promise.resolve()
                } else {
                  return Promise.reject(new Error('请输入大于0的值'))
                }
              }
            }
          ]}>
            <Input></Input>
          </Form.Item>
          <Form.Item name="min" label="支付min" rules={[
            { 
              required: true,
              validator: (_, value) => {
                if (value > 0) {
                  return Promise.resolve()
                } else {
                  return Promise.reject(new Error('请输入大于0的值'))
                }
              }
            }
          ]}>
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
} 